package com.gxc.healthfood.controller;

import com.gxc.healthfood.common.ResponseResult;
import com.gxc.healthfood.entity.Foods;
import com.gxc.healthfood.entity.FoodNutrients;
import com.gxc.healthfood.service.FoodsService;
import com.gxc.healthfood.service.FoodNutrientsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;

/**
 * 食物管理控制器
 */
@RestController
@RequestMapping("/food")
public class FoodController {

    private static final Logger log = LoggerFactory.getLogger(FoodController.class);

    @Autowired
    private FoodsService foodsService;

    @Autowired
    private FoodNutrientsService foodNutrientsService;

    /**
     * 添加食物
     * @param request 食物请求数据，包含食物基本信息和营养成分
     * @return 添加结果
     */
    @PostMapping
    public ResponseResult<Map<String, Object>> addFood(@RequestBody Map<String, Object> request) {
        try {
            // 1. 验证请求参数
            if (!validateFoodRequest(request)) {
                return ResponseResult.error("请求参数不完整或无效");
            }

            String name = (String) request.get("name");
            // 处理categoryId字段，支持多种数值类型转换
            Integer categoryId = null;
            try {
                Object categoryIdObj = request.get("categoryId");
                if (categoryIdObj instanceof Integer) {
                    categoryId = (Integer) categoryIdObj;
                } else if (categoryIdObj instanceof Long) {
                    categoryId = ((Long) categoryIdObj).intValue();
                } else if (categoryIdObj instanceof Double) {
                    categoryId = ((Double) categoryIdObj).intValue();
                } else if (categoryIdObj instanceof Float) {
                    categoryId = ((Float) categoryIdObj).intValue();
                } else if (categoryIdObj instanceof String) {
                    categoryId = Integer.parseInt((String) categoryIdObj);
                } else {
                    // 尝试将其他类型转换为字符串再转换为Integer
                    categoryId = Integer.parseInt(categoryIdObj.toString());
                }
            } catch (Exception e) {
                log.error("categoryId类型转换失败: {}", e.getMessage());
                return ResponseResult.error("分类ID格式错误");
            }
            Map<String, Object> nutrientsMap = (Map<String, Object>) request.get("nutrients");

            // 2. 检查食物名称是否已存在
            if (foodsService.findByName(name) != null) {
                return ResponseResult.error("食物名称已存在");
            }

//            // 3. 验证营养成分数据
//            if (!validateNutrients(nutrientsMap)) {
//                System.out.println(nutrientsMap);
//                return ResponseResult.error("营养成分不能为负数");
//            }

            // 4. 保存食物基本信息
            Foods food = new Foods();
            food.setName(name);
            food.setCategoryId(categoryId);
            food.setDescription((String) request.getOrDefault("description", ""));
            food.setServingSize((String) request.getOrDefault("servingSize", "100g"));
            // 处理ediblePercentage字段，支持多种数值类型转换
            if (request.containsKey("ediblePercentage")) {
                try {
                    Object ediblePercentageObj = request.get("ediblePercentage");
                    if (ediblePercentageObj instanceof BigDecimal) {
                        food.setEdiblePercentage((BigDecimal) ediblePercentageObj);
                    } else if (ediblePercentageObj instanceof Integer) {
                        food.setEdiblePercentage(BigDecimal.valueOf((Integer) ediblePercentageObj));
                    } else if (ediblePercentageObj instanceof Long) {
                        food.setEdiblePercentage(BigDecimal.valueOf((Long) ediblePercentageObj));
                    } else if (ediblePercentageObj instanceof Double) {
                        food.setEdiblePercentage(BigDecimal.valueOf((Double) ediblePercentageObj));
                    } else if (ediblePercentageObj instanceof Float) {
                        food.setEdiblePercentage(BigDecimal.valueOf((Float) ediblePercentageObj));
                    } else {
                        // 尝试将其他类型转换为字符串再转换为BigDecimal
                        food.setEdiblePercentage(new BigDecimal(ediblePercentageObj.toString()));
                    }
                } catch (Exception e) {
                    log.error("ediblePercentage类型转换失败: {}", e.getMessage());
                    food.setEdiblePercentage(new BigDecimal("100.00")); // 默认值
                }
            } else {
                food.setEdiblePercentage(new BigDecimal("100.00"));
            }
            food.setImageUrl((String) request.getOrDefault("imageUrl", null));
            // 处理isCommon字段，支持多种数值类型转换
            if (request.containsKey("isCommon")) {
                try {
                    Object isCommonObj = request.get("isCommon");
                    if (isCommonObj instanceof Integer) {
                        food.setIsCommon((Integer) isCommonObj);
                    } else if (isCommonObj instanceof Long) {
                        food.setIsCommon(((Long) isCommonObj).intValue());
                    } else if (isCommonObj instanceof Double) {
                        food.setIsCommon(((Double) isCommonObj).intValue());
                    } else if (isCommonObj instanceof Float) {
                        food.setIsCommon(((Float) isCommonObj).intValue());
                    } else if (isCommonObj instanceof String) {
                        food.setIsCommon(Integer.parseInt((String) isCommonObj));
                    } else {
                        // 尝试将其他类型转换为字符串再转换为Integer
                        food.setIsCommon(Integer.parseInt(isCommonObj.toString()));
                    }
                } catch (Exception e) {
                    log.error("isCommon类型转换失败: {}", e.getMessage());
                    food.setIsCommon(1); // 默认值
                }
            } else {
                food.setIsCommon(1);
            }
            food.setSource((String) request.getOrDefault("source", "USER"));
            // 处理createdBy字段，支持多种数值类型转换
            if (request.containsKey("createdBy")) {
                try {
                    Object createdByObj = request.get("createdBy");
                    if (createdByObj instanceof Long) {
                        food.setCreatedBy((Long) createdByObj);
                    } else if (createdByObj instanceof Integer) {
                        food.setCreatedBy(((Integer) createdByObj).longValue());
                    } else if (createdByObj instanceof Double) {
                        food.setCreatedBy(((Double) createdByObj).longValue());
                    } else if (createdByObj instanceof Float) {
                        food.setCreatedBy(((Float) createdByObj).longValue());
                    } else if (createdByObj instanceof String) {
                        food.setCreatedBy(Long.parseLong((String) createdByObj));
                    } else {
                        // 尝试将其他类型转换为字符串再转换为Long
                        food.setCreatedBy(Long.parseLong(createdByObj.toString()));
                    }
                } catch (Exception e) {
                    log.error("createdBy类型转换失败: {}", e.getMessage());
                    food.setCreatedBy(null); // 默认值
                }
            } else {
                food.setCreatedBy(null);
            }
            food.setCreatedAt(new Date());
            food.setUpdatedAt(new Date());

            boolean foodSaved = foodsService.save(food);
            if (!foodSaved) {
                return ResponseResult.error("保存食物基本信息失败");
            }

            // 5. 保存营养成分
            FoodNutrients nutrients = new FoodNutrients();
            nutrients.setFoodId(food.getId());
            // 处理营养成分字段，支持多种数值类型转换
            try {
                // 处理calories
                nutrients.setCalories(convertToBigDecimal(nutrientsMap.get("calories"), "calories"));
                // 处理protein
                nutrients.setProtein(convertToBigDecimal(nutrientsMap.get("protein"), "protein"));
                // 处理fat
                nutrients.setFat(convertToBigDecimal(nutrientsMap.get("fat"), "fat"));
                // 处理carbohydrate
                nutrients.setCarbohydrate(convertToBigDecimal(nutrientsMap.get("carbohydrate"), "carbohydrate"));
            } catch (Exception e) {
                log.error("营养成分类型转换失败: {}", e.getMessage());
                foodsService.removeById(food.getId());
                return ResponseResult.error("营养成分数据格式错误");
            }
            nutrients.setCreatedAt(new Date());
            nutrients.setUpdatedAt(new Date());

            boolean nutrientsSaved = foodNutrientsService.save(nutrients);
            if (!nutrientsSaved) {
                // 如果营养成分保存失败，删除已保存的食物
                foodsService.removeById(food.getId());
                return ResponseResult.error("保存营养成分失败");
            }

            // 6. 返回完整的食物信息
            Map<String, Object> result = getFoodInfoWithNutrients(food.getId());
            return ResponseResult.success("食物添加成功", result);

        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.error("系统异常，请稍后重试");
        }
    }

    /**
     * 更新食物
     * @param id 食物ID
     * @param request 更新的食物数据
     * @return 更新结果
     */
    @PutMapping("/{id}")
    public ResponseResult<Map<String, Object>> updateFood(@PathVariable Long id, @RequestBody Map<String, Object> request) {
        try {
            // 检查食物是否存在
            Foods existingFood = foodsService.getById(id);
            if (existingFood == null) {
                return ResponseResult.error("食物不存在");
            }

            // 检查食物名称是否重复（如果修改了名称）
            if (request.containsKey("name")) {
                String newName = (String) request.get("name");
                if (!newName.equals(existingFood.getName())) {
                    if (foodsService.findByName(newName) != null) {
                        return ResponseResult.error("食物名称已存在");
                    }
                    existingFood.setName(newName);
                }
            }

            // 更新其他基本信息
            if (request.containsKey("categoryId")) {
                try {
                    Object categoryIdValue = request.get("categoryId");
                    Integer categoryId = null;
                    if (categoryIdValue instanceof Integer) {
                        categoryId = (Integer) categoryIdValue;
                    } else if (categoryIdValue instanceof Long) {
                        categoryId = ((Long) categoryIdValue).intValue();
                    } else if (categoryIdValue instanceof Double) {
                        categoryId = ((Double) categoryIdValue).intValue();
                    } else if (categoryIdValue instanceof Float) {
                        categoryId = ((Float) categoryIdValue).intValue();
                    } else if (categoryIdValue != null) {
                        // 尝试将其他类型转换为字符串，再转换为Integer
                        try {
                            categoryId = Integer.parseInt(categoryIdValue.toString());
                        } catch (NumberFormatException e) {
                            log.error("Failed to convert categoryId to Integer: {}", e.getMessage());
                            return ResponseResult.error("分类ID格式错误");
                        }
                    }
                    existingFood.setCategoryId(categoryId);
                } catch (Exception e) {
                    log.error("Error converting categoryId: {}", e.getMessage());
                    return ResponseResult.error("分类ID格式错误");
                }
            }
            if (request.containsKey("description")) {
                existingFood.setDescription((String) request.get("description"));
            }
            if (request.containsKey("servingSize")) {
                existingFood.setServingSize((String) request.get("servingSize"));
            }
            if (request.containsKey("ediblePercentage")) {
                Object ediblePercentageValue = request.get("ediblePercentage");
                if (ediblePercentageValue != null) {
                    if (ediblePercentageValue instanceof BigDecimal) {
                        existingFood.setEdiblePercentage((BigDecimal) ediblePercentageValue);
                    } else if (ediblePercentageValue instanceof Integer) {
                        existingFood.setEdiblePercentage(BigDecimal.valueOf((Integer) ediblePercentageValue));
                    } else if (ediblePercentageValue instanceof Long) {
                        existingFood.setEdiblePercentage(BigDecimal.valueOf((Long) ediblePercentageValue));
                    } else if (ediblePercentageValue instanceof Double) {
                        existingFood.setEdiblePercentage(BigDecimal.valueOf((Double) ediblePercentageValue));
                    } else if (ediblePercentageValue instanceof Float) {
                        existingFood.setEdiblePercentage(BigDecimal.valueOf((Float) ediblePercentageValue));
                    } else {
                        // 尝试将其他类型转换为字符串，再转换为BigDecimal
                        try {
                            existingFood.setEdiblePercentage(new BigDecimal(ediblePercentageValue.toString()));
                        } catch (NumberFormatException e) {
                            log.error("Failed to convert ediblePercentage to BigDecimal: " + e.getMessage());
                            // 可以选择抛出异常或使用默认值
                        }
                    }
                }
            }
            if (request.containsKey("imageUrl")) {
                existingFood.setImageUrl((String) request.get("imageUrl"));
            }
            if (request.containsKey("isCommon")) {
                try {
                    Object isCommonValue = request.get("isCommon");
                    Integer isCommon = null;
                    if (isCommonValue instanceof Integer) {
                        isCommon = (Integer) isCommonValue;
                    } else if (isCommonValue instanceof Long) {
                        isCommon = ((Long) isCommonValue).intValue();
                    } else if (isCommonValue instanceof Double) {
                        isCommon = ((Double) isCommonValue).intValue();
                    } else if (isCommonValue instanceof Float) {
                        isCommon = ((Float) isCommonValue).intValue();
                    } else if (isCommonValue != null) {
                        // 尝试将其他类型转换为字符串，再转换为Integer
                        try {
                            isCommon = Integer.parseInt(isCommonValue.toString());
                        } catch (NumberFormatException e) {
                            log.error("Failed to convert isCommon to Integer: {}", e.getMessage());
                            return ResponseResult.error("通用标识格式错误");
                        }
                    }
                    existingFood.setIsCommon(isCommon);
                } catch (Exception e) {
                    log.error("Error converting isCommon: {}", e.getMessage());
                    return ResponseResult.error("通用标识格式错误");
                }
            }
            if (request.containsKey("source")) {
                existingFood.setSource((String) request.get("source"));
            }
            if (request.containsKey("createdBy")) {
                try {
                    Object createdByValue = request.get("createdBy");
                    Long createdBy = null;
                    if (createdByValue instanceof Long) {
                        createdBy = (Long) createdByValue;
                    } else if (createdByValue instanceof Integer) {
                        createdBy = ((Integer) createdByValue).longValue();
                    } else if (createdByValue instanceof Double) {
                        createdBy = ((Double) createdByValue).longValue();
                    } else if (createdByValue instanceof Float) {
                        createdBy = ((Float) createdByValue).longValue();
                    } else if (createdByValue != null) {
                        // 尝试将其他类型转换为字符串，再转换为Long
                        try {
                            createdBy = Long.parseLong(createdByValue.toString());
                        } catch (NumberFormatException e) {
                            log.error("Failed to convert createdBy to Long: {}", e.getMessage());
                            return ResponseResult.error("创建者ID格式错误");
                        }
                    }
                    existingFood.setCreatedBy(createdBy);
                } catch (Exception e) {
                    log.error("Error converting createdBy: {}", e.getMessage());
                    return ResponseResult.error("创建者ID格式错误");
                }
            }
            existingFood.setUpdatedAt(new Date());

            // 保存更新后的基本信息
            boolean foodUpdated = foodsService.updateById(existingFood);
            if (!foodUpdated) {
                return ResponseResult.error("更新食物基本信息失败");
            }

            // 更新营养成分
            if (request.containsKey("nutrients")) {
                Map<String, Object> nutrientsMap = (Map<String, Object>) request.get("nutrients");
                
//                // 验证营养成分
//                if (!validateNutrients(nutrientsMap)) {
//                    return ResponseResult.error("营养成分不能为负数");
//                }

                // 查找或创建营养成分记录
                FoodNutrients existingNutrients = foodNutrientsService.getByFoodId(id);
                if (existingNutrients == null) {
                    existingNutrients = new FoodNutrients();
                    existingNutrients.setFoodId(id);
                    existingNutrients.setCreatedAt(new Date());
                }

                // 更新营养成分数据
                try {
                    existingNutrients.setCalories(convertToBigDecimal(nutrientsMap.get("calories"), "calories"));
                    existingNutrients.setProtein(convertToBigDecimal(nutrientsMap.get("protein"), "protein"));
                    existingNutrients.setFat(convertToBigDecimal(nutrientsMap.get("fat"), "fat"));
                    existingNutrients.setCarbohydrate(convertToBigDecimal(nutrientsMap.get("carbohydrate"), "carbohydrate"));
                } catch (IllegalArgumentException e) {
                    log.error("Nutrient data format error: {}", e.getMessage());
                    return ResponseResult.error("营养成分数据格式错误");
                }
                existingNutrients.setUpdatedAt(new Date());

                boolean nutrientsUpdated = foodNutrientsService.saveOrUpdate(existingNutrients);
                if (!nutrientsUpdated) {
                    return ResponseResult.error("更新营养成分失败");
                }
            }

            // 返回更新后的完整食物信息
            Map<String, Object> result = getFoodInfoWithNutrients(id);
            return ResponseResult.success("食物更新成功", result);

        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.error("系统异常，请稍后重试");
        }
    }

    /**
     * 查询食物列表
     * @param page 页码，默认1
     * @param pageSize 每页数量，默认10
     * @param keyword 搜索关键词
     * @param categoryId 分类ID
     * @return 食物列表
     */
    @GetMapping
    public ResponseResult<Map<String, Object>> getFoodList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) Integer categoryId) {
        try {
            // 构建查询条件
            Map<String, Object> conditions = new HashMap<>();
            if (keyword != null && !keyword.isEmpty()) {
                conditions.put("keyword", keyword);
            }
            if (categoryId != null) {
                conditions.put("categoryId", categoryId);
            }

            // 查询食物列表
            List<Map<String, Object>> foodList = foodsService.findFoodsWithNutrients(page, pageSize, conditions);
            long total = foodsService.countFoodsWithConditions(conditions);

            Map<String, Object> result = new HashMap<>();
            result.put("list", foodList);
            result.put("total", total);
            result.put("page", page);
            result.put("pageSize", pageSize);
            result.put("totalPages", (total + pageSize - 1) / pageSize);

            return ResponseResult.success("获取成功", result);

        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.error("系统异常，请稍后重试");
        }
    }

    /**
     * 获取食物详情
     * @param id 食物ID
     * @return 食物详情
     */
    @GetMapping("/{id}")
    public ResponseResult<Map<String, Object>> getFoodDetail(@PathVariable Long id) {
        try {
            // 检查食物是否存在
            Foods food = foodsService.getById(id);
            if (food == null) {
                return ResponseResult.error("食物不存在");
            }

            // 获取食物详情（包含营养成分）
            Map<String, Object> result = getFoodInfoWithNutrients(id);
            return ResponseResult.success("获取成功", result);

        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.error("系统异常，请稍后重试");
        }
    }

    /**
     * 删除食物
     * @param id 食物ID
     * @return 删除结果
     */
    @DeleteMapping("/{id}")
    public ResponseResult<Map<String, Object>> deleteFood(@PathVariable Long id) {
        try {
            // 检查食物是否存在
            Foods food = foodsService.getById(id);
            if (food == null) {
                return ResponseResult.error("食物不存在");
            }

            // 删除食物（营养成分会通过外键级联删除）
            boolean deleted = foodsService.removeById(id);
            if (deleted) {
                Map<String, Object> result = new HashMap<>();
                result.put("message", "食物删除成功");
                return ResponseResult.success("删除成功", result);
            } else {
                return ResponseResult.error("删除失败，请稍后重试");
            }

        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.error("系统异常，请稍后重试");
        }
    }

    /**
     * 验证食物请求参数
     */
    private boolean validateFoodRequest(Map<String, Object> request) {
        return request.containsKey("name") && 
               request.containsKey("categoryId") &&
               request.containsKey("nutrients") &&
               request.get("name") instanceof String &&
               request.get("categoryId") instanceof Integer &&
               request.get("nutrients") instanceof Map;
    }

    /**
     * 验证营养成分数据
     */
    private boolean validateNutrients(Map<String, Object> nutrients) {
        if (nutrients == null) return false;
        
        try {
            java.math.BigDecimal calories = (java.math.BigDecimal) nutrients.get("calories");
            java.math.BigDecimal protein = (java.math.BigDecimal) nutrients.get("protein");
            java.math.BigDecimal fat = (java.math.BigDecimal) nutrients.get("fat");
            java.math.BigDecimal carbohydrate = (java.math.BigDecimal) nutrients.get("carbohydrate");

            return calories != null && calories.compareTo(java.math.BigDecimal.ZERO) >= 0 &&
                   protein != null && protein.compareTo(java.math.BigDecimal.ZERO) >= 0 &&
                   fat != null && fat.compareTo(java.math.BigDecimal.ZERO) >= 0 &&
                   carbohydrate != null && carbohydrate.compareTo(java.math.BigDecimal.ZERO) >= 0;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 获取食物详情（包含营养成分）
     */
    private Map<String, Object> getFoodInfoWithNutrients(Long foodId) {
        // 获取食物基本信息
        Foods food = foodsService.getById(foodId);
        if (food == null) return null;

        // 获取营养成分
        FoodNutrients nutrients = foodNutrientsService.getByFoodId(foodId);

        // 构建返回结果
        Map<String, Object> foodInfo = new HashMap<>();
        foodInfo.put("id", food.getId());
        foodInfo.put("name", food.getName());
        foodInfo.put("categoryId", food.getCategoryId());
        foodInfo.put("description", food.getDescription());
        foodInfo.put("servingSize", food.getServingSize());
        foodInfo.put("ediblePercentage", food.getEdiblePercentage());
        foodInfo.put("imageUrl", food.getImageUrl());
        foodInfo.put("isCommon", food.getIsCommon());
        foodInfo.put("source", food.getSource());
        foodInfo.put("createdBy", food.getCreatedBy());
        foodInfo.put("createdAt", food.getCreatedAt());
        foodInfo.put("updatedAt", food.getUpdatedAt());

        // 添加营养成分信息
        if (nutrients != null) {
            Map<String, Object> nutrientInfo = new HashMap<>();
            nutrientInfo.put("calories", nutrients.getCalories());
            nutrientInfo.put("protein", nutrients.getProtein());
            nutrientInfo.put("fat", nutrients.getFat());
            nutrientInfo.put("carbohydrate", nutrients.getCarbohydrate());
            foodInfo.put("nutrients", nutrientInfo);
        }

        return foodInfo;
    }

    /**
     * 将各种类型的数值安全地转换为BigDecimal
     * @param value 要转换的值
     * @param fieldName 字段名，用于日志记录
     * @return 转换后的BigDecimal值
     * @throws IllegalArgumentException 当值为null或无法转换时抛出
     */
    private BigDecimal convertToBigDecimal(Object value, String fieldName) {        
        if (value == null) {
            throw new IllegalArgumentException(fieldName + " cannot be null");
        }
        
        try {
            if (value instanceof BigDecimal) {
                return (BigDecimal) value;
            } else if (value instanceof Integer) {
                return BigDecimal.valueOf((Integer) value);
            } else if (value instanceof Long) {
                return BigDecimal.valueOf((Long) value);
            } else if (value instanceof Double) {
                return BigDecimal.valueOf((Double) value);
            } else if (value instanceof Float) {
                return BigDecimal.valueOf((Float) value);
            } else if (value instanceof String) {
                return new BigDecimal((String) value);
            } else {
                // 尝试将其他类型转换为字符串再转换为BigDecimal
                return new BigDecimal(value.toString());
            }
        } catch (Exception e) {
            throw new IllegalArgumentException("Failed to convert " + fieldName + " to BigDecimal: " + e.getMessage(), e);
        }
    }
}